# -*- coding:utf-8 -*-

from fastapi import Depends, HTTPException, status, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from fastapi.responses import JSONResponse
from services.user import UserService
from schemas.user import User

from utils.password import virify_password, password_hash
from utils.jwt import create_access_token, create_refresh_token, Token, get_token_data

async def auth_login(form_data: OAuth2PasswordRequestForm = Depends(), service: UserService = Depends(UserService)):
    data_db = await service.first(User.from_orm({'account': form_data.username}))
    if data_db is None:
        # raise HTTPException(status_code=400, detail="Incorrect username or password")
        return JSONResponse(status_code=400, content={"message": "Incorrect username or password"})
    if not virify_password(form_data.password, data_db.password):
        # raise HTTPException(status_code=400, detail="Incorrect username or password")
        return JSONResponse(status_code=400, content={"message": "Incorrect username or password"})
    access_token = create_access_token({"sub": form_data.username})
    refresh_token = create_refresh_token({"sub": form_data.username})
    # return success(data={"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"})
    return Token(access_token=access_token, refresh_token=refresh_token, token_type="bearer")


async def auth_refresh_token(token_data: dict=Depends(get_token_data), service: UserService = Depends(UserService)):
    data_db = await service.first(User.from_orm({'account': form_data.username}))
    if data_db is None:
        raise HTTPException(status_code=400, detail="token超时,请重新登录")
    access_token = create_access_token({"sub": data_db.account})
    refresh_token = create_refresh_token({"sub": data_db.account})
    # return success(data={"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"})
    return Token(access_token=access_token, refresh_token=refresh_token, token_type="bearer")



